<template>
  <div class="fillcontain">
    <!-- <div class="head-title"><i class="el-icon-edit-outline">规则组详情</i></div> -->
    <bt-col-header title="规则组详情"></bt-col-header>
    <div class="page-content">
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="80px"
        class="form-container"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="规则组标识"
              label-width="120px"
              prop="groupIdentify"
            >
              <el-input
                v-model="dataForm.groupIdentify"
                placeholder="规则组标识"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则组名称" label-width="120px" prop="groupName">
              <el-input
                disabled
                v-model="dataForm.groupName"
                placeholder="规则组名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="是否有效" label-width="120px" prop="isEffect">
              <el-switch
                disabled
                v-model="dataForm.isEffect"
                active-color="#13ce66"
                inactive-color="#ff4949"
                on-value="1" on-text="是" off-text="否" off-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="规则组描述" label-width="120px" prop="groupDesc">
          <el-input
            disabled
            type="textarea"
            :rows="3"
            v-model="dataForm.groupDesc"
            placeholder="规则组描述"
          ></el-input>
        </el-form-item>

        <el-row>
          <el-form-item label="关联模型" label-width="120px">
            <el-checkbox-group
              v-model="checkEntity"
              @change="handleCheckedChange"
              disabled
            >
              <el-col
                :span="12"
                v-for="entity in entitysProperties"
                :key="entity.entityId"
              >
                <el-checkbox
                  :label="entity.entityId + ''"
                  :key="entity.entityId"
                  >{{ entity.label }}</el-checkbox
                >
              </el-col>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
      </el-form>  
    
    
      <div class="mb10 pl20">
        <!-- <div class="content-title"><span>决策表</span></div> -->
        <bt-col-header title="决策表"></bt-col-header>
        <div class="page-content">
          <div class="">
            <el-table :data="tableDatas" border height="500">
              <el-table-column
                v-for="(col, i) in conditionList"
                :render-header="labelHead"
                :property="col.decisionCode"
                :key="col.decisionCode"
                :index="i"
                align="center"
                :label="col.conditionDesc"
              >
                <template slot="header" slot-scope="scope">
                  <el-tooltip
                    v-if="
                      conditionList[scope.column.index] &&
                      conditionList[scope.column.index].headType == '0'
                    "
                    class="item"
                    effect="dark"
                    :content="scope.column.label"
                    placement="top"
                  >
                    <span> {{ scope.column.label }} </span>
                  </el-tooltip>
                  <el-tooltip
                    v-if="
                      conditionList[scope.column.index] &&
                      conditionList[scope.column.index].headType == '1'
                    "
                    class="item"
                    effect="dark"
                    :content="scope.column.label + '(条件)'"
                    placement="top"
                  >
                    <span> {{ scope.column.label }} (条件) </span>
                  </el-tooltip>
                  <el-tooltip
                    v-if="
                      conditionList[scope.column.index] &&
                      conditionList[scope.column.index].headType == '2'
                    "
                    class="item"
                    effect="dark"
                    :content="scope.column.label + '(动作)'"
                    placement="top"
                  >
                    <span> {{ scope.column.label }} (动作) </span>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <div v-if="scope.row[scope.column.property]">
                    {{ scope.row[scope.column.property].conditionDesc }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        
      </div>
      <div class="view-footer">
        <el-button style="width: 100px; margin-bottom: 20px" @click="toList"
          >返&nbsp;&nbsp;回</el-button
        >
      </div>
    </div>
    
  </div>
</template>

<script>
import { saveData, getData, saveRuleGroup } from "@/api/ruleConfig/groupInfo";
import { entityList } from "@/api/baseConfig/entity";
import { pageData, updateData } from "@/api/ruleConfig/rule";
import constant from "@/api/constant";

import { getDecisionsByGroup } from "@/api/ruleConfig/decision";

export default {
  data() {
    return {
      checktaskdes: { demandName: "选择任务" },
      checktaskarry: [],
      entityList: [],
      conditionList: [],
      tableDatas: [], //决策表数据
      groupTypes: constant.ruleConfig.groupTypes,
      checkEntity: [],
      dataList: [],
      dataForm: {
        id: null,
        groupName: "",
        groupDesc: "",
        groupIdentify: "",
        remark: "",
        groupType: "1",
        isEffect: "1",
      },
      entitysProperties: [],
      dataRule: {
        groupName: [
          { required: true, message: "规则组名称不能为空", trigger: "blur" },
          { max: 50, message: "长度不能大于50", trigger: "blur" },
        ],
        groupType: [
          { required: true, message: "规则组类型不能为空", trigger: "blur" },
        ],
      },
      itemDataForm: {
        itemData: [],
      },
      page: {
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
      },
    };
  },
  created() {},
  components: {},

  mounted() {
    // console.log(this.$route.query);
    let id = this.$route.params.id;
    let type = this.$route.params.type;
    if (this.$route.query) {
      this.$parent.demandName = this.$route.query.TASK_NO;
      // console.log(this.$parent, "$pa");
    }
    this.init(id, type);
  },
  methods: {
    labelHead: function (h, { column, $index }) {
      let l = column.label.length;
      let f = 16;
      column.minWidth = f * (l + 2); //加上一个文字长度
      return h("div", { class: "table-head", style: { width: "100%" } }, [
        column.label,
      ]);
    },
    checktask(val) {
      // console.log(val);
      this.checktaskdes = val;
    },
    toList() {
      // console.log(this.$route.query);
      if (this.$route.query.viewTask) {
        this.$router.push({
          path: `/drools-version/view-task/${this.$route.query.task_no}`,
        });
      } else if (this.$route.query.lcgl) {
        if (this.$route.query.lcgl === "lcglxz") {
          // 返回流程管理新增页
          this.$router.push({
            path: `/drools-ruleConfig/flow/edit-flow/${this.$route.query.task_no}`,
          });
        } else if (this.$route.query.lcgl === "lcglbj") {
          // 返回流程编辑页
          this.$router.push({
            path: `/drools-ruleConfig/flow/edit-flow/${this.$route.query.bj.id}/${this.$route.query.bj.rowTaskNo}/${this.$route.query.bj.taskNo}/${this.$route.query.bj.flowIdentify}`,
          });
        } else if (this.$route.query.lcgl === "lcglck") {
          this.$router.push({
            path: `/drools-ruleConfig/flow/view-flow/${this.$route.query.bj.id}/${this.$route.query.bj.rowTaskNo}/${this.$route.query.bj.taskNo}/${this.$route.query.bj.flowIdentify}`,
          });
        }
      } else if (this.$route.query.address === "rulegrouplist") {
        this.$router.push({
          path: `/drools-version/rulegrouplist`,
        });
      } else {
        this.$router.push({ path: "/drools-ruleConfig/group/list" });
      }
    },
    handleCheckedChange(data) {
      // console.log(data);
    },
    init(id, type) {
      this.entitysProperties = [];
      this.checkEntity = [];
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.getEntityProperties();
        if (id && id != "undefined") {
          this.dataForm.id = id;
          this.isDisabled = true;
          let params = {
            id: this.dataForm.id + "",
            groupType: type,
          };
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          getData(params)
            .then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.data.data && res.data.resultCode === 0) {
                this.dataForm = res.data.data.groupInfo;
                this.initDecision(type);
                res.data.data.relList.forEach((item) => {
                  this.checkEntity.push(item.entityId + "");
                });
              }
            })
            .catch((err) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
            });
        }
      });
    },
    //初始化规则组下已有决策表信息
    initDecision(type) {
      let params = {
        groupIdentify: this.dataForm.groupIdentify,
        taskNo: this.dataForm.taskNo,
        type: type,
        version: this.dataForm.groupVersion + "",
      };
      // console.log(this.dataForm.groupIdentify);
      // this.$store.dispatch("loading/CHANGE_LOADING", true);
      getDecisionsByGroup(params)
        .then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if (res.data.data) {
            this.tableDatas = res.data.data.body;
            // console.log(this.tableDatas, "eDatas");
            this.conditionList = res.data.data.head;
            //除去规则名称和编码的表头
            if (this.conditionList && this.conditionList.length > 0) {
              // this.tempHeaderList =[]
              this.conditionList.forEach((item) => {
                if (
                  item.decisionCode != "RNAME" &&
                  item.decisionCode != "RCODE"
                ) {
                  // this.tempHeaderList.push(item)
                }
              });
            } else {
              this.ruleList.forEach((item) => {
                this.conditionList.push(item);
              });
            }
            this.tableDatas.forEach((ele, index) => {
              this.conditionList.forEach((item) => {
                // console.log(ele[item.decisionCode]);
                if (!ele[item.decisionCode]) {
                  this.tableDatas.splice(index, 1);
                }
              });
            });
            // console.log("初始化头部信息:" + JSON.stringify(this.conditionList));
          }
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });
    },
    // 获取实体类的属性
    getEntityProperties() {
      entityList({}).then((res) => {
        if (res.data.data) {
          this.entitysProperties = [];
          res.data.data.forEach((item) => {
            item["label"] = item.entityIdentify + " -- " + item.entityName;
            this.entitysProperties.push(item);
          });
        }
      });
    },
    // 决策表单提交
    dataFormSubmit() {
      // console.log(this.$refs["desionOrUpdate"]);
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.itemDataForm.itemData = [];
          // console.log(this.checkEntity);
          this.checkEntity.forEach((item) => {
            this.entitysProperties.forEach((e) => {
              if (item === e.entityId + "") {
                let entity = {
                  entityName: e.entityName,
                  entityIdentify: e.entityIdentify,
                  entityId: e.entityId,
                };
                this.itemDataForm.itemData.push(entity);
              }
            });
          });
          // console.log(this.itemDataForm.itemData);
          if (this.itemDataForm.itemData.length <= 0) {
            this.$message.error("请先关联模型");
            return;
          }
          let values = [];
          let tableDatas = this.$refs.desionOrUpdate.tableDatas;
          let conditionList = this.$refs.desionOrUpdate.conditionList;
          if (tableDatas.length > 0) {
            for (var i = 0; i < tableDatas.length; i++) {
              let data = tableDatas[i];
              if (data) {
                conditionList.forEach((item) => {
                  // console.log(data, conditionList);
                  if (data[item.decisionCode]) {
                    data[item.decisionCode]["rowIndex"] = i;
                    values.push(data[item.decisionCode]);
                  }
                });
              }
            }
          }
          if (localStorage.getItem("checktaskobj")) {
            // console.log(JSON.parse(localStorage.getItem("checktaskobj")));
            let checktaskobj = JSON.parse(localStorage.getItem("checktaskobj"));
            var taskInfo = { taskNo: checktaskobj.taskNo };
          }
          // let { taskNo: val.taskNo};
          let params = {
            groupInfo: JSON.stringify(this.dataForm),
            relList: JSON.stringify(this.itemDataForm.itemData),
            heads: JSON.stringify(this.$refs.desionOrUpdate.conditionList),
            values: JSON.stringify(values),
            delList: JSON.stringify(this.$refs.desionOrUpdate.delList),
            delHeadList: JSON.stringify(this.$refs.desionOrUpdate.delHeadList),
            taskInfo: JSON.stringify(taskInfo),
          };
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          saveRuleGroup(params)
            .then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.data && res.data.resultCode === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.dataForm = {
                      id: null,
                      groupName: "",
                      groupDesc: "",
                      groupIdentify: "",
                      remark: "",
                      isEffect: "1",
                    };
                    this.itemDataForm.itemData = [];
                    this.entitysProperties = [];
                    this.checkEntity = [];
                    // this.$emit('refreshDataList')
                    this.toList();
                  },
                });
              } else {
                this.$message.error(res.data.resultMsg);
              }
            })
            .catch((err) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
            });
        }
      });
    },
  },
  filters: {
    isEffectFilter: function (value) {
      let label = "";
      if (value === "0") {
        label = "失效";
      } else if (value === "1") {
        label = "有效";
      }
      return label;
    },
  },
};
</script>

<style lang="scss">
.el-table__row .el-form-item__content {
  margin-left: 0 !important;
}

.el-table__row .el-form-item {
  margin-bottom: 0 !important;
}
</style>
<style lang="less" scoped>
body .el-table th.gutter {
  display: table-cell !important;
}
.current-task {
  margin: 20px;
  span {
    font-size: 16px;
    font-weight: 900;
    margin-right: 10px;
  }
  .el-dropdown span {
    font-size: 14px;
    color: #ff0000;
  }
}
.view-footer {
  width: 100%;
  display: flex;
  justify-content: center;
  align-self: center;
}
</style>
